<?php

class SessionManager {
	
	/**
	 *  @var int 
	*/
	private static $lastErrorCode = -1;
	
	function __construct(){
		
	}
	
	/**
	 * Creates a session with the given credentails. 
	 * If the credentials are invalid null is returned.
	 * If the login is successfull the session ID is returned
	 * 
	 * @param string $name
	 * @param string $password
	 * 
	 * @return string sessionID or null
	 */
	public static function login($name, $password){
		if(User::checkLogin($name, md5($password))){
			session_start();
			$_SESSION['USER_IP'] = $_SERVER['REMOTE_ADDR'];
			$user = User::getUserByName($name);
			$_SESSION['USER_ID'] = $user->getID();
			$_SESSION['USER_NAME'] = $name;
			$_SESSION['USER_PASSWORD'] = md5($password);
			$_SESSION['START_TIME'] = time();
			return session_id();
		} else {
			SessionManager::$lastErrorCode = ERROR_INVALID_LOGIN;
			return null;
		}
	}
	
	/**
	 * Continues the session with the given ID and returns true if successfull.
	 * If session continuation fails false is returned.
	 * 
	 * @param string $sessionID
	 * 
	 * @return boolean
	 */
	public static function continueSession($sessionID){
		session_id($sessionID);
		if(session_id() != ''){
			if(session_start()){
				if(isset($_SESSION['START_TIME'])){
					if($_SESSION['USER_IP'] == $_SERVER['REMOTE_ADDR']){
						if(User::checkLogin($_SESSION['USER_NAME'], $_SESSION['USER_PASSWORD'])){
							return true;
						} else {
							SessionManager::$lastErrorCode = ERROR_INVALID_LOGIN;
							return false;
						}
					} else {
						SessionManager::$lastErrorCode = ERROR_INVALID_IP;
						return false;
					} 
				} else {
					SessionManager::$lastErrorCode = ERROR_SESSION_EXPIRED;
					return false;
				} 
			} else {
					SessionManager::$lastErrorCode = ERROR_SESSION_START_FAILED;
					return false;
			}
		} else {
			SessionManager::$lastErrorCode = ERROR_INVALID_SESSION_ID;
			return false;
		}
	}
	
	/**
	 * Stops the currently active session
	 * 
	 * @param string $sessionID
	 * 
	 * @return boolean
	 */
	public static function stopSession(){
		if(session_destroy()){
			return true;
		} else {
			SessionManager::$lastErrorCode = ERROR_STOP_SESSION_FAILED;
			return false;
		}
	}
	
	/**
	 * Returns the error code for the last occured error or -1 if no error occurred.
	 * @return int error code
	 */
	public static function getLastError(){
		return SessionManager::$lastErrorCode;
	}
	
}

?>